<template>
  <div>
    <!-- Modify dialog start -->
    <el-dialog
        v-model="modifyVisible"
        title="修改脚本"
        width="30%"
        align-center
    >
      <div>
        <el-form :model="modifyData" status-icon ref="modifyRef" label-width="80px" class="demo-ruleForm">
          <el-form-item label="名称" prop="scriptName">
            <el-input v-model="modifyData.scriptName"></el-input>
          </el-form-item>
          <div style="margin-top: 20px">
            <el-radio-group v-model="radio2">
              <el-radio-button label="前处理脚本" />
              <el-radio-button label="后处理脚本" />
            </el-radio-group>
          </div>

          <el-form-item style="margin: 20px auto auto;">
            <el-button type="primary" @click="modifySubmitForms">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- Modify dialog end -->

    <!-- ADD dialog start -->
    <el-dialog
        v-model="dialogVisible"
        title="Warning"
        width="30%"
        align-center
    >
      <div>
        <el-form :model="makeData" status-icon ref="formRef" label-width="80px" class="demo-ruleForm">
          <el-form-item label="名称" prop="scriptName">
            <el-input v-model="makeData.scriptName"></el-input>
          </el-form-item>
          <div style="margin-top: 20px">
            <el-radio-group v-model="radio2">
              <el-radio-button label="前处理脚本" />
              <el-radio-button label="后处理脚本" />
            </el-radio-group>
          </div>

          <input type="file" @change="uploadFiles">
          <div class="drop_box">
            将文件拖到此区域进行上传
          </div>

          <el-form-item style="margin: 20px auto auto;">
            <el-button type="primary" @click="submitForms">提交</el-button>
            <el-button @click="resetForm('signUp')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- ADD dialog start -->


    <!-- lsit_data start -->
    <div class="list_data_box">
      <div class="line"></div>
      <div class="gui_box">
        <el-input
            v-model="input3"
            placeholder="Please input"
            class="input-with-select"
        >
          <template #append>
            <el-button :icon="Search" />
          </template>
        </el-input>
        <el-button @click="dialogVisible = true" type="primary" style="margin-left: 288px;">创建脚本</el-button>
        <el-button type="danger" :icon="Delete" @click="removeView"/>
      </div>

      <el-table :data="listData" v-model:selected-keys="selectedKeys" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="scriptId" label="脚本Id"></el-table-column>
        <el-table-column prop="scriptName" label="脚本名称"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="tag" label="描述"></el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button :icon="EditPen" @click="modifyView(row)" style="border: none;">修改</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- lsit_data end -->

  </div>
</template>

<script>
import {ElDialog, ElForm, ElLoading, ElMessage, ElMessageBox} from "element-plus";
import {onMounted, reactive, ref} from "vue";
import script from "@/api/script";
import imgs from "@/api/imgs";
import {Delete, Search, EditPen} from "@element-plus/icons-vue";

export default {
  name: "Scripts",
  components:{
    ElDialog,
    ElLoading,
    ElForm
  },
  setup(){
    // 文本渲染
    const msg = ref('hello')

    // 控制创建数据集的弹出层，默认为不弹出
    const dialogVisible = ref(false)
    let loadingInstance = null

    // form数据模型
    const makeData = ref({
      scriptName:'',
    })
    const formRef = ref(null)
    const formData = new FormData();

    // 渲染数据模型
    let listData = reactive([])
    const selectedKeys = reactive([])

    // 选择数据模型
    const scriptIds = []

    // 描述选择框
    const radio2 = ref('前脚本')

    // form修改数据模型
    const modifyData = ref({
      imgName:'',
    })
    const modifyRef = ref(null)
    let modifyId = 0
    const modifyVisible = ref(false)


    /// 函数区
    // 加载函数
    onMounted(()=>{
      getList()
    });

    // 查
    function getList(){
      console.log("被调用：")
      let userData = JSON.parse(localStorage.getItem('userData'))

      let da = {}
      da.userId = userData.userId
      script.list(da).then(res => {
        listData.length = 0
        res.data.forEach(function(element){
          if(element.tag === 0){
            element.tag = "前处理脚本"
          }else{
            element.tag = "后处理脚本"
          }
        })
        listData.splice(0,res.data.length,...res.data)
        listData.forEach(function(element){
          console.log(element.createTime.replace('T','\n'))
          element.createTime = element.createTime.replace('T',' ')
        })
      })
    }

    // 删
    function removeView(){
      if(scriptIds.length === 0){
        ElMessageBox.alert('请勾选想要删除的数据！','Warning',{
          confirmButtonText:"OK"
        })
      }else{
        ElMessageBox.confirm(
            '您确定想要删除选中的数据集吗？',
            'Warning',
            {
              confirmButtonText:'OK',
              cancelButtonText:'Cancel',
              type: 'warning'
            }
        ).then(() => {
          script.remove(scriptIds).then(res => {
            console.log(res)
            if(res.code == 200){
              ElMessage.success("删除成功")
              getList()
              scriptIds.splice(0,scriptIds.length)
            }
          })
        }).catch(() => {
          ElMessage({
            type:'info',
            message:"取消删除"
          })
        })
      }
    }

    // 关闭遮罩层
    function handleBeforeClose(done){
      loadingInstance.close()
      done()
    }

    // 增
    const submitForms = () => {
      formRef.value.validate((valid) => {
        if(valid){
          let tag = "0"
          if(radio2.value == "前处理脚本"){
            tag = "0"
          }else{
            tag = "1"
          }
          formData.append("Ids[]",makeData.value.scriptName)
          formData.append("Ids[]",tag)
          formData.append("Ids[]",JSON.parse(localStorage.getItem('userData')).userId.toString())

          script.make(formData).then(res =>{
            console.log(res)
            if(res.code == 200){
              console.log(res)
              ElMessage.success("创建成功")
              getList()
            }else{
              ElMessage.error("error！")
            }
          })
        }else{
          ElMessage.error("error！")
          return false
        }
      })
    }

    // 改
    const modifyView = (row) => {
      console.log(row)
      modifyVisible.value = true
      modifyData.value.scriptName = row.scriptName
      modifyId = row.scriptId
      radio2.value = row.tag
    };

    // 改 提交
    const modifySubmitForms = () => {
      modifyRef.value.validate((valid) => {
        if(valid){
          let da = {}
          da.scriptName = modifyData.value.scriptName;
          da.scriptId = modifyId
          let tag = "0"
          if(radio2.value == "前处理脚本"){
            tag = "0"
          }else{
            tag = "1"
          }
          da.tag = tag
          console.log(da)
          script.modify(da).then(res =>{
            console.log(res)
            if(res.code == 200){
              console.log(res)
              ElMessage.success("修改成功")
              getList()
            }else{
              ElMessage.error("error！")
            }
          })

        }else{
          ElMessage.error("error！")
          return false
        }
      })
    }

    // 加载文件
    function uploadFiles(event){
      const files = event.target.files;

      for(let i=0;i < files.length; i++){
        const file = files[i]
        let id = Date.now() + i
        if(file.type == "text/x-python"){
          formData.append("files[]",file, id.toString());
          formData.append("names[]",file.name);
        }else{
          ElMessage.error("请上传Python文件")
        }
      }
    }

    // 控制选择
    const handleSelectionChange = (selection) => {
      if(scriptIds.length !== 0){
        scriptIds.splice(0,scriptIds.length)
      }
      selection.forEach((item) =>{
        scriptIds.push(item.scriptId)
      })
    }

    return {
      dialogVisible,
      handleBeforeClose,
      makeData,
      submitForms,
      formRef,
      listData,
      removeView,
      selectedKeys,
      handleSelectionChange,
      uploadFiles,
      radio2,
      modifyRef,
      modifyData,
      modifySubmitForms,
      modifyView,
      modifyVisible,
      Delete,
      Search,
      EditPen
    }
  }
}
</script>

<style scoped>
.list_data_box{
  width:100%;
  height: 100vh;
  padding:0;
  margin-top: 22px
}
.el-table{
  width: 87.7% !important;
  text-align: initial;
  /*height: 115px;*/
  background-color: rgb(255 255 255 / 60%);
  /*border: 1px solid*/
  color: #8c8ca3;
  margin-left:15px
}
.gui_box{
  background-color: rgb(255 255 255 / 60%);
  border-bottom: 2px solid #d9d9d9;
  width: 87.7%;
  height: 55px;
  margin-left:15px
}
.el-input-group{
  width: 30%;
  left: 10px;
}
.line{
  height: 25px;
  width: 87.7%;;
  background-color: rgb(255 255 255 / 60%);
  margin-left:15px;
  border-radius: 10px 10px 0 0;
}
</style>